import { computed, onBeforeUnmount, ref } from 'vue'
import moment from 'moment'
import { string } from 'vue-types'
export function useDateHubs() {
  /**
   * 生成一个倒计时的string compute
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @param intervalSecond 差值秒数
   */
  function generateCountDownString(
    startTime?: string,
    endTime?: string,
    intervalSecond: number = 1
  ) {
    if (!endTime) endTime = moment().format('YYYY-MM-DD HH:mm:ss')
    if (!startTime) startTime = moment().format('YYYY-MM-DD HH:mm:ss')
    const second = moment(endTime).diff(moment(startTime), 'seconds')
    return generateCountDownBase(second, intervalSecond)
  }

  /**
   * 生成一个倒计时的string compute
   * @param second 总共倒计时时间
   * @param intervalSecond 差值秒数
   */
  function generateCountDownBase(second: number, intervalSecond: number = 1) {
    const seconds = ref(second)
    let timer: number = 0
    // 设置一个定时器
    function startTimer() {
      timer = setInterval(() => {
        seconds.value -= intervalSecond
        // console.log('seconds =' + seconds)
      }, intervalSecond * 1000)
    }

    // 注销定时期
    onBeforeUnmount(() => {
      if (timer) {
        clearInterval(timer)
      }
    })

    // 清理
    startTimer()
    return computed(() => {
      const { day, hour, minute, second } = formatTime(seconds.value)
      return `${day}天${hour}时${minute}分${second}秒`
    })
  }
  return {
    generateCountDownString,
    generateCountDownBase,
  }
}

// 格式化时间
function formatTime(
  seconds: number,
  showDays: boolean = true
): { [key: string]: number } {
  // 小于等于0的话，结束倒计时
  if (!seconds) {
    return {}
  }
  let [day, hour, minute, second] = [0, 0, 0, 0]
  day = Math.floor(seconds / (60 * 60 * 24))
  // 判断是否显示“天”参数，如果不显示，将天部分的值，加入到小时中
  // hour为给后面计算秒和分等用的(基于显示天的前提下计算)
  hour = Math.floor(seconds / (60 * 60)) - day * 24
  // showHour为需要显示的小时
  let showHour = null
  if (showDays) {
    showHour = hour
  } else {
    showHour = Math.floor(seconds / (60 * 60))
  }
  minute = Math.floor(seconds / 60) - hour * 60 - day * 24 * 60
  second =
    Math.floor(seconds) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60
  return { day, hour: showHour, minute, second }
}
